package com.quzi.kettle.view;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import net.simonvt.numberpicker.NumberPicker;
import net.simonvt.numberpicker.NumberPicker.OnValueChangeListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.quzi.kettle.R;
import com.quzi.kettle.utils.DateUtils;

public class MNumberPicker {
	public static final int PICKER_TYPE_DATE = 1;
	public static final int PICKER_TYPE_TIME = 2;
	public static final int PICKER_TYPE_TIME12 = 3;

	private static final int REFRESH_DAY = 111;
	private int[] yearShowsData;
	private String[] dayShowsData;
	private NumberPicker hourNP;
	private NumberPicker minteNP;
	private NumberPicker yearNP;
	private NumberPicker monthNP;
	private NumberPicker dayNP;
	private String[] monthShowsData;
	private int currType;
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
	private int mMinte;
	private int ampm;
	private int mHour12;
	private int mMinte12;
	protected View popuWindowLayout;
	protected PopupWindow popupWindow;
	private ViewGroup baseViewGroup;
	private LinearLayout dateLayout;
	private LinearLayout timeLayout;
	private Date currDate;
	private String nian;
	private String yue;
	private String ri;
	private Context context;
	private Display display;
	private LayoutInflater layoutInflater;
	private MNumberReceive numberReceive;

	private Handler mHandler = new Handler() {
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case REFRESH_DAY:
				initDayData();
				break;
			}
		};
	};
	private LinearLayout time12Layout;
	private NumberPicker ampm_12NP;
	private NumberPicker hour_12NP;
	private NumberPicker minte_12NP;
	private Button cancleBtn;
	private TextView title;

	private int mheight;

	public MNumberPicker(Context context, int height) {
		this.context = context;
		this.mheight = height;
	}

	/**
	 * 
	 */
	public void initNumberPicker(Display display,
			LayoutInflater layoutInflater, ViewGroup baseLayout) {
		this.display = display;
		this.layoutInflater = layoutInflater;
		this.baseViewGroup = baseLayout;
		currDate = new Date(System.currentTimeMillis());
		initPupoWindow();
		nian = this.context.getString(R.string.nian);
		yue = this.context.getString(R.string.yue);
		ri = this.context.getString(R.string.ri);

		initYearData();
		initMonthData();
		initDayData();
		initTime();
		initTime12();
	}

	public void setCancleButtonText(String str) {
		if (str.isEmpty()) {
			cancleBtn.setVisibility(View.GONE);
		} else {
			cancleBtn.setVisibility(View.VISIBLE);
			cancleBtn.setText(str);
		}
	}

	public void setTitle(String str) {
		if (str.isEmpty()) {
			title.setVisibility(View.GONE);
		} else {
			title.setVisibility(View.VISIBLE);
			title.setText(str);
		}
	}

	private void initPupoWindow() {
		popuWindowLayout = layoutInflater.inflate(
				R.layout.center_layout_mnubmer_picker, null);

		dateLayout = (LinearLayout) popuWindowLayout
				.findViewById(R.id.mnumber_date_layout);
		timeLayout = (LinearLayout) popuWindowLayout
				.findViewById(R.id.mnubmer_time_layout);
		time12Layout = (LinearLayout) popuWindowLayout
				.findViewById(R.id.mnubmer_time_layout_12);

		yearNP = (NumberPicker) popuWindowLayout
				.findViewById(R.id.mnumPicker_year);
		monthNP = (NumberPicker) popuWindowLayout
				.findViewById(R.id.mnumPicker_month);
		dayNP = (NumberPicker) popuWindowLayout
				.findViewById(R.id.mnumPicker_day);
		hourNP = (NumberPicker) popuWindowLayout
				.findViewById(R.id.mnumPicker_hour);
		minteNP = (NumberPicker) popuWindowLayout
				.findViewById(R.id.mnumPicker_minte);

		ampm_12NP = (NumberPicker) popuWindowLayout
				.findViewById(R.id.mnumPicker_ampm_12);
		hour_12NP = (NumberPicker) popuWindowLayout
				.findViewById(R.id.mnumPicker_hour_12);
		minte_12NP = (NumberPicker) popuWindowLayout
				.findViewById(R.id.mnumPicker_minte_12);

		cancleBtn = (Button) popuWindowLayout
				.findViewById(R.id.numberpicker_cancle);
		Button okBtn = (Button) popuWindowLayout
				.findViewById(R.id.numberpicker_ok);
		title = (TextView) popuWindowLayout.findViewById(R.id.title);
		cancleBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (numberReceive != null) {
					numberReceive.leftBtnClick();
				}
				popupWindow.dismiss();
			}
		});
		okBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				boolean canDiss = true;

				if (currType == PICKER_TYPE_DATE) {
					mYear = yearNP.getValue();
					mMonth = monthNP.getValue();
					mDay = dayNP.getValue();
				} else if (currType == PICKER_TYPE_TIME) {
					mHour = hourNP.getValue();
					mMinte = minteNP.getValue();
				} else {
					ampm = ampm_12NP.getValue();
					mHour12 = hour_12NP.getValue() + init_hour;
					mMinte12 = minte_12NP.getValue();
					if (isHour && isToday) {
						Date date = new Date(System.currentTimeMillis());
						Calendar c = Calendar.getInstance();
						c.setTime(date);
						mMinte12 += c.get(Calendar.MINUTE);
					}
				}

				if (numberReceive != null) {
					if (currType == PICKER_TYPE_DATE) {
						canDiss = numberReceive.checkCanDiss(currType, mYear,
								mMonth, mDay);
					} else if (currType == PICKER_TYPE_TIME) {
						canDiss = numberReceive.checkCanDiss(currType, mHour,
								mMinte);
					} else {
						canDiss = numberReceive.checkCanDiss(currType, ampm,
								mHour12, mMinte12);
					}
				}
				Log.w("DateString", "canPass: " + canDiss);

				if (!canDiss) {
					return;
				}

				if (currType == PICKER_TYPE_DATE) {
					updateDate();
				} else if (currType == PICKER_TYPE_TIME) {
					updateTime();
				} else {
					Log.d("mmqtt", "update Callbacks " + mMinte12);
					updateTime12();
				}
				popupWindow.dismiss();
			}
		});

		popupWindow = new PopupWindow(popuWindowLayout, display.getWidth(),
				mheight);
		popupWindow.setTouchable(true);
		popupWindow.setOutsideTouchable(false);
		popupWindow.setFocusable(true);
		// 设置后点击外部会消失
		// popupWindow.setBackgroundDrawable(new BitmapDrawable(
		// context.getResources(), (Bitmap) null));

		// popupWindow.setTouchInterceptor(new View.OnTouchListener() {
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// /**** 如果点击了popupwindow的外部，popupwindow也会消失 ****/
		// if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
		// popupWindow.dismiss();
		// return true;
		// }
		// return false;
		// }
		// });

	}

	public void dismiss() {
		popupWindow.dismiss();
	}

	public boolean isShowing() {
		return popupWindow.isShowing();
	}

	public void setCurrTimeValue(int hour, int min) {
		this.mHour = hour;
		this.mMinte = min;
		hourNP.setValue(mHour);
		minteNP.setValue(mMinte);
	}

	public void setCurrTime12Value(int ampm, int hour, int min) {
		this.ampm = ampm;
		this.mHour12 = hour;
		this.mMinte12 = min;
		ampm_12NP.setValue(ampm);
		hour_12NP.setValue(mHour12 - 1);
		minte_12NP.setValue(mMinte12);
	}

	public void setCurrDateValue(int year, int month, int day) {
		this.mYear = year;
		this.mMonth = month;
		this.mDay = day;
	}

	public void showNumberPicker(int type) {
		currType = type;
		if (type == PICKER_TYPE_DATE) {
			dateLayout.setVisibility(View.VISIBLE);
			timeLayout.setVisibility(View.GONE);
			time12Layout.setVisibility(View.GONE);
		} else if (type == PICKER_TYPE_TIME) {
			timeLayout.setVisibility(View.VISIBLE);
			dateLayout.setVisibility(View.GONE);
			time12Layout.setVisibility(View.GONE);
		} else {
			time12Layout.setVisibility(View.VISIBLE);
			timeLayout.setVisibility(View.GONE);
			dateLayout.setVisibility(View.GONE);
		}
		popupWindow.setAnimationStyle(R.style.popupAnimation);
		popupWindow.showAtLocation(baseViewGroup, Gravity.BOTTOM, 0, 0);

		hour_12NP.setValue(0);
		isHour = false;
		isToday = true;
		minte_12NP.invalidate();
		hour_12NP.invalidate();

	}

	private void initYearData() {
		int currYear = currDate.getYear() + 1900;
		yearShowsData = new int[2];
		yearShowsData[0] = currYear;
		yearShowsData[1] = currYear + 1;
		String[] yearsStr = { String.valueOf(yearShowsData[0]) + nian,
				String.valueOf(yearShowsData[1]) + nian };

		yearNP.setMaxValue(yearShowsData[1]);
		yearNP.setMinValue(yearShowsData[0]);

		yearNP.setDisplayedValues(yearsStr);
		yearNP.setFocusable(true);
		yearNP.setFocusableInTouchMode(true);
		yearNP.setValue(0);

		yearNP.setOnValueChangedListener(new OnValueChangeListener() {

			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				Log.i("ShowNuberPicker", "year: " + newVal);
				mYear = newVal;
				mHandler.sendEmptyMessageDelayed(REFRESH_DAY, 1000);
			}
		});
		mYear = yearNP.getValue();
	}

	/**
	 * 获取可用的时间段
	 * 
	 * @param isToday
	 *            是否今天 true/今天 false/明天
	 * @return [Hour.start;Hour.end;Minute.start;Minute.end]
	 */
	private int[] getAvailableTime(boolean ishour, boolean isToday) {
		Log.d("MNUMBER", "ishour = " + ishour + "   isToday = " + isToday);
		int currHour = DateUtils.getCurrHour();
		int currMinute = DateUtils.getCurrMinute();
		int[] result = new int[4];
		result[0] = 0;
		result[1] = 23;
		result[2] = 0;
		result[3] = 59;
		if (isToday) {
			if (ishour) {
				result[2] = currMinute;
			}
			result[0] = currHour;
		} else {
			if (ishour) {
				result[3] = currMinute;
			}
			result[1] = currHour;
		}

		init_hour = result[0];
		init_minute = result[2];
		Log.d("MNUMBER", "Hour.start = " + result[0] + "  Hour.end = "
				+ result[1] + "  Minute.start = " + result[2]
				+ "   Minute.end = " + result[3]);

		return result;
	}

	private boolean isToday = true;
	private boolean isHour = true;

	private boolean isHourb = true;
	private boolean isTodayb = true;

	private void updatePicker(NumberPicker picker, String[] newValues) {
		picker.setDisplayedValues(null);
		picker.setMinValue(0);
		picker.setMaxValue(newValues.length - 1);
		picker.setWrapSelectorWheel(true);
		picker.setDisplayedValues(newValues);

	}

	int init_hour = 0;
	int init_minute = 0;

	private void initTime12() {
		ampm_12NP.setMaxValue(1);
		ampm_12NP.setMinValue(0);
		String[] displayAMPM = { "今天", "明天" };
		ampm_12NP.setFocusable(true);
		ampm_12NP.setFocusableInTouchMode(true);
		ampm_12NP.setDisplayedValues(displayAMPM);
		ampm_12NP.setValue(0);
		ampm_12NP.setOnValueChangedListener(new OnValueChangeListener() {
			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				ampm = newVal;
				Log.d("MNUMBER", "当前时间 天 = " + newVal);
				if (newVal == 0) {
					isToday = true;
				} else {
					isToday = false;
				}
				if (isToday != isTodayb) {
					int[] result = getAvailableTime(isHour, isToday);
					isTodayb = isToday;

					String[] displayMin = getDisplayValue(result[2], result[3]);
					updatePicker(minte_12NP, displayMin);
					String[] displayHour = getDisplayValue(result[0], result[1]);
					updatePicker(hour_12NP, displayHour);

					hour_12NP.setMaxValue(result[1] - result[0]);
					Log.d("PICKER", "VALUE = " + (result[1] - result[0]));
					hour_12NP.setMinValue(0);
					hour_12NP.invalidate();
				} else {

				}
			}
		});

		if (isToday != isTodayb) {
			int[] result = getAvailableTime(isHour, isToday);
			isTodayb = isToday;

			String[] displayMin = getDisplayValue(result[2], result[3]);
			updatePicker(minte_12NP, displayMin);
			String[] displayHour = getDisplayValue(result[0], result[1]);
			updatePicker(hour_12NP, displayHour);

			hour_12NP.setMaxValue(result[1] - result[0]);
			Log.d("PICKER", "VALUE = " + (result[1] - result[0]));
			hour_12NP.setMinValue(0);
			hour_12NP.invalidate();
		} else {

		}

		int[] result = getAvailableTime(isHour, isToday);
		hour_12NP.setMaxValue(result[1] - result[0]);
		hour_12NP.setMinValue(0);

		String[] displayHour = getDisplayValue(result[0], result[1]);
		hour_12NP.setDisplayedValues(displayHour);
		hour_12NP.setFocusable(true);
		hour_12NP.setFocusableInTouchMode(true);
		int hour = DateUtils.getCurrHour();
		hour_12NP.setValue(hour);
		hour_12NP.setOnValueChangedListener(new OnValueChangeListener() {
			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				mHour12 = newVal;
				if (Integer.valueOf(picker.getDisplayedValues()[newVal]) == DateUtils
						.getCurrHour()) {
					isHour = true;
				} else {
					isHour = false;
				}

				if (isHour != isHourb || isToday != isTodayb) {
					int[] result_min = getAvailableTime(isHour, isToday);
					isHourb = isHour;

					String[] displayMin = getDisplayValue(result_min[2],
							result_min[3]);

					updatePicker(minte_12NP, displayMin);
					String[] displayHour = getDisplayValue(result_min[0],
							result_min[1]);
					updatePicker(hour_12NP, displayHour);

					minte_12NP.setMaxValue(result_min[3] - result_min[2]);
					minte_12NP.setMinValue(0);
					minte_12NP.invalidate();
				}

			}
		});

		if (isHour != isHourb || isToday != isTodayb) {
			int[] result_min = getAvailableTime(isHour, isToday);
			isHourb = isHour;

			String[] displayMin = getDisplayValue(result_min[2], result_min[3]);

			updatePicker(minte_12NP, displayMin);
			String[] mdisplayHour = getDisplayValue(result_min[0],
					result_min[1]);
			updatePicker(hour_12NP, mdisplayHour);

			minte_12NP.setMaxValue(result_min[3] - result_min[2]);
			minte_12NP.setMinValue(0);
			minte_12NP.invalidate();
		}

		Log.d("abcd", "初始化 minute_12NP = " + result[2] + "  " + result[3]);

		int[] result_min = getAvailableTime(isHour, isToday);
		minte_12NP.setMaxValue(result_min[3]);
		minte_12NP.setMinValue(result_min[2]);
		String[] displayMin = getDisplayValue(result_min[2], result_min[3]);
		minte_12NP.setDisplayedValues(displayMin);
		minte_12NP.setFocusable(true);
		minte_12NP.setFocusableInTouchMode(true);
		// minte_12NP.setValue(DateUtils.getCurrMinute());
		minte_12NP.setOnValueChangedListener(new OnValueChangeListener() {
			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				mMinte12 = newVal;
				Log.d("mmqtt", "minute12 = " + mMinte12);
			}
		});
	}

	@SuppressWarnings("deprecation")
	private void initMonthData() {
		monthShowsData = context.getResources().getStringArray(
				R.array.yuyue_month_date);
		int month = currDate.getMonth() + 1;

		monthNP.setMaxValue(12);
		monthNP.setMinValue(1);
		monthNP.setDisplayedValues(monthShowsData);
		monthNP.setFocusable(true);
		monthNP.setFocusableInTouchMode(true);
		monthNP.setValue(month);
		mMonth = month;
		monthNP.setOnValueChangedListener(new OnValueChangeListener() {

			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				Log.i("ShowNumberPicker", "month: " + newVal);
				mMonth = newVal;
				mHandler.sendEmptyMessageDelayed(REFRESH_DAY, 1000);
			}
		});

	}

	private void initTime() {
		hourNP.setMaxValue(23);
		hourNP.setMinValue(0);
		// hourNP.setDisplayedValues(timeData);
		hourNP.setFocusable(true);
		hourNP.setFocusableInTouchMode(true);
		String[] displayHour = getDisplayValue(0, 24);
		hourNP.setDisplayedValues(displayHour);
		hourNP.setValue(0);
		hourNP.setOnValueChangedListener(new OnValueChangeListener() {
			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				mHour = newVal;
			}
		});

		String[] displayMin = getDisplayValue(0, 60);
		minteNP.setMaxValue(59);
		minteNP.setMinValue(0);
		minteNP.setDisplayedValues(displayMin);
		minteNP.setFocusable(true);
		minteNP.setFocusableInTouchMode(true);
		minteNP.setValue(0);
		minteNP.setOnValueChangedListener(new OnValueChangeListener() {
			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				mMinte = newVal;
			}
		});
	}

	private String[] getDisplayValue(int fromNum, int toNum) {
		String[] displayHour = new String[toNum - fromNum + 1];
		for (int i = 0; i < toNum - fromNum + 1; i++) {
			String temp = null;
			if ((i + fromNum) < 10) {
				temp = "0" + (i + fromNum);
			} else {
				temp = String.valueOf((i + fromNum));
			}
			displayHour[i] = temp;
		}
		return displayHour;
	}

	/**
	 * @return
	 */
	// private String[] getDisplayValue(int size) {
	// String[] displayHour = new String[size];
	// for (int i = 0; i < displayHour.length; i++) {
	// String temp = null ;
	// if(i < 10){
	// temp = "0"+i;
	// }else{
	// temp = String.valueOf(i);
	// }
	// displayHour[i] = temp ;
	// }
	// return displayHour;
	// }

	private void initDayData() {
		int date = mMonth;
		int monthRes = R.array.yuyue_month_day_data_31;
		switch (date) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			monthRes = R.array.yuyue_month_day_data_31;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			monthRes = R.array.yuyue_month_day_data_30;
			break;
		case 2:
			if (checkRunNian()) {
				monthRes = R.array.yuyue_month_day_data_29;
			} else {
				monthRes = R.array.yuyue_month_day_data_28;
			}
			break;
		}

		dayShowsData = context.getResources().getStringArray(monthRes);

		Log.i("ShowNumberPicker", "size: " + dayShowsData.length + " : "
				+ Arrays.toString(dayShowsData));
		dayNP.setMaxValue(dayShowsData.length);
		dayNP.setMinValue(1);
		dayNP.setValue(mDay);
		dayNP.setFocusable(true);
		dayNP.setFocusableInTouchMode(true);

		dayNP.setOnValueChangedListener(new OnValueChangeListener() {

			@Override
			public void onValueChange(NumberPicker picker, int oldVal,
					int newVal) {
				mDay = newVal;
			}
		});

	}

	/**
	 * 判断是否闰年
	 * 
	 * @return
	 */
	private boolean checkRunNian() {
		boolean result = false;
		int currYear = currDate.getYear() + 1900;
		if (currYear % 4 == 0 && currYear % 100 != 0 || currYear % 400 == 0) {
			// 是闰年
			result = true;
		} else {
			// 不是闰年
		}
		return result;
	}

	public void updateDate() {
		if (numberReceive != null) {
			numberReceive.updateDate(mYear, mMonth, mDay);
		}
	}

	public void updateTime() {
		if (numberReceive != null) {
			numberReceive.updateTime(mHour, mMinte);
		}
	}

	public void updateTime12() {
		if (numberReceive != null) {
			Log.d("mmqtt", "mMinute12 = " + mMinte12);
			numberReceive.updateTime12(ampm, mHour12, mMinte12);
		}
	}

	public MNumberReceive getNumberReceive() {
		return numberReceive;
	}

	public void setNumberReceive(MNumberReceive numberReceive) {
		this.numberReceive = numberReceive;
	}

}
